"use strict";

// 递归做Object 深拷贝，使用refMap 避免循环引用 导致 死循环
function deepCopyWithRefMap(obj, refMap) {
    let newobj = null;
    if (typeof (obj) == 'object' && obj !== null) {
        if (refMap.get(obj)) {
            
            newobj = refMap.get(obj) // 避免循环引用，如果不想循环打印 可以设置为null
            console.log("func deepCopyWithRefMap, loop ref found");
            console.dir(obj);
            console.dir(newobj);
        } else {
            newobj = obj instanceof Array ? [] : {};
            refMap.set(obj, newobj)
            for (var i in obj) {
                newobj[i] = deepCopyWithRefMap(obj[i], refMap);
            }
        }

    } else {
        newobj = obj
    }
    return newobj;
}

function deepClone(obj) {
    var refMap = new Map();
    return deepCopyWithRefMap(obj, refMap);
}

function dicLoop() {
    let monthDic = {
        "January": 31,
        "February": 28,
        "March": 31,
        "April": 30,
        "May": 31,
        "June": 30,
        "July": 31,
        "August": 31,
        "September": 30,
        "October": 31,
        "November": 30,
        "December": 31,
    };

    console.log("type of monthDic : " + typeof (monthDic));

    for (var key in monthDic) {
        console.log("for in : " + key + ", " + monthDic[key]);
    }

    // 循环引用构造
    let loopRefTest = deepClone(monthDic);
    loopRefTest["loopRef"] = loopRefTest;
    for (var key in loopRefTest) {
        console.log("loopRefTest for in : " + key + ", " + loopRefTest[key]);
    }

    // 有循环引用的Object 做 深拷贝
    let loopRefCloneTest = deepClone(loopRefTest);
    for (var key in loopRefCloneTest) {
        console.log("loopRefCloneTest for in : " + key + ", " + loopRefCloneTest[key]);
    }
}


function dicSort() {
    let monthDic = {
        "January": 31,
        "February": 28,
        "March": 31,
        "April": 30,
        "May": 31,
        "June": 30,
        "July": 31,
        "August": 31,
        "September": 30,
        "October": 31,
        "November": 30,
        "December": 31,
    };

    for (var key of Object.keys(monthDic).sort()) {
        console.log("sorted key : " + key + ", " + monthDic[key]);
    }

    let sorted = Object.keys(monthDic).sort((a, b) => {
        let secA = a.substring(1, 2);
        let secB = b.substring(1, 2);
        let diff = secA.localeCompare(secB); // 对于字符串来说，如果 secA 全等 secB 返回0，如果 secA 字母序 小于 secB, 返回 -1， 否则返回 1
        console.log("sort func, secA=" + secA + ", secB=" + secB + ", diff=" + diff);
        return diff; // 返回 -1 表示升序排序，a 排在 b 前面（a 比 b小）

        //return a.substring(1,2).localeCompare(b.substring(1, 2));
    })

    for (var key of sorted) {
        console.log("key按第二个字母排序 : " + key + ", " + monthDic[key]);
    }
}


function demoLogic() {
    console.log("\ndicDemoLogic");

    dicLoop();

    dicSort();
}

//module.exports.deepClone = deepClone;
//module.exports.demoLogic = demoLogic;

export{demoLogic, deepClone};